package io.sdl.common.sys.service.impl;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;
/*
 * 在线状态管理
 */
@Service
public class OnlineUserService {

    private static final String ONLINE_USERS_KEY = "online_users";
    private final RedisTemplate<String, String> redisTemplate;

    public OnlineUserService(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void userOnline(String userId) {
        redisTemplate.opsForSet().add(ONLINE_USERS_KEY, userId);
        // 设置过期时间，防止用户断线后一直显示在线
        redisTemplate.expire(ONLINE_USERS_KEY, 5, TimeUnit.MINUTES);
    }

    public void userOffline(String userId) {
        redisTemplate.opsForSet().remove(ONLINE_USERS_KEY, userId);
    }

    public boolean isUserOnline(String userId) {
        return redisTemplate.opsForSet().isMember(ONLINE_USERS_KEY, userId);
    }

    public Set<String> getOnlineUsers() {
        return redisTemplate.opsForSet().members(ONLINE_USERS_KEY);
    }
}
